const connection = require('../../util/rabbitmq');


// const onMessage = data => {
//     const message = JSON.parse(data.content.toString());
//     console.log('subscriber: got message :: ', message);
//     this.channelWrapper.ack(data);
// }
const QUEUE_NAME= 'myqueuebins10';
const EXCHANGE_NAME='myexchang10';
const TYPE_NAME='fanout';
class AmqpSubscriber {
    constructor() {
        this.channelWrapper = connection.createChannel({
            json: true,
            setup: channel => 
                Promise.all([
                    channel.assertQueue(QUEUE_NAME),
                    channel.assertExchange(EXCHANGE_NAME, TYPE_NAME, {durable: false}),
                    channel.prefetch(1),
                    channel.bindQueue(QUEUE_NAME, EXCHANGE_NAME, ''),
                    channel.consume(QUEUE_NAME, data => {
                        console.log('subscriber: got message :: ', JSON.parse(data.content.toString()));
                        console.log('subscriber: got fields :: ', data.fields);
                        console.log('subscriber: got headers :: ', data.properties.headers);
                        console.log('subscriber: got headers[userId] :: ', data.properties.headers.userId);
                        console.log('subscriber: got headers[tenantId] :: ', data.properties.headers.tenantId);
                        // this.channelWrapper.ack(data);
                    }, {noAck: true})
                ])
            // confirm: false
        });
        
        this.channelWrapper.waitForConnect().then(function () {
            console.log('Listening for messages');
        });
    }
}

module.exports = new AmqpSubscriber();